package com.wxx.service.bg;

import com.google.common.base.Splitter;
import com.wxx.common.Const;
import com.wxx.mapper.DicAclMapper;
import com.wxx.mapper.DicRoleAclMapper;
import com.wxx.model.DicUser;
import com.wxx.util.CookieUtil;
import com.wxx.util.JsonData;
import com.wxx.util.JsonUtil;
import com.wxx.util.RedisPoolUtil;
import com.wxx.vo.AclZtreeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Service
public class DicRoleAclServiceImpl implements DicRoleAclService {

    @Autowired
    private DicRoleAclMapper roleAclMapper;
    @Autowired
    private DicAclMapper aclMapper;

    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public Map addRoleAcl(HttpServletRequest request, String nodeString, String roleId) {
        //先删除该角色的权限
        roleAclMapper.delByRoleId(roleId);

        List<String> stringList = Splitter.on(",").splitToList(nodeString);

        //批量新增权限
        Integer num = roleAclMapper.addRoleAcl(roleId,stringList);

        //todo 判断修改的是否是当前权限，如果是就要更新权限 ok
        String sessionId = CookieUtil.readLoginToken(request);

        if (StringUtils.isNotBlank(sessionId)){
            String userJson = RedisPoolUtil.get(sessionId);
            DicUser dicUser = JsonUtil.string2Obj(userJson, DicUser.class);
            if (dicUser!=null){
                if (dicUser.getRoleId().equals(roleId)) {
                    //查询权限路径集合
                    List<String> allURIByRoleId = aclMapper.findAllURIByRoleId(dicUser.getRoleId());
                    //最新的集合放入到redis中
                    RedisPoolUtil.set(sessionId+Const.CURRENT_URIBYROLEID, JsonUtil.obj2String(allURIByRoleId));
                }
            }
        }

        return JsonData.returnMap(num);
    }

    @Override
    public List<AclZtreeVo> findAssemblyAcl(String roleId) {
        //查询所有的权限
        List<AclZtreeVo> aclZtreeVoList = aclMapper.findAllAclZtree();

        //根据当前人登录的roleId查询该角色的权限id
        List<String> stringList = roleAclMapper.findAclIdByRoleId(roleId);
        for (AclZtreeVo aclZtreeVo : aclZtreeVoList) {
            //登录人id的权限是否在总权限中存在
            if (stringList.contains(aclZtreeVo.getId())){
                aclZtreeVo.setChecked(true);
            }else{
                aclZtreeVo.setChecked(false);
            }
        }

        return aclZtreeVoList;
    }
}
